import { chatActonType } from '../actionTypes';
import { chatContextType, ChatHistoryResponse, IChatDialogueMessageSchema } from '@/types/chat';

interface IChatContext {
  chatContexts: chatContextType[];
  history: ChatHistoryResponse;
  currentDialog?: IChatDialogueMessageSchema;
}

const initialState: IChatContext = {
  chatContexts: [],
  history: [],
};

type ActionType = {
  type: string;
  payload?: any;
};

function updateChatById(chatContexts: chatContextType[], chatContext: chatContextType) {
  // 查找是否有匹配的id
  const foundIndex = chatContexts.findIndex((item) => item.chatid === chatContext.chatid);

  if (foundIndex !== -1) {
    // 如果找到了，则更新该对象
    chatContexts[foundIndex] = chatContext;
  } else {
    // 如果没找到，则创建一个新的对象并添加到数组中，title为内容的前8个
    chatContexts = [chatContext, ...chatContexts];
  }
  return chatContexts;
}

function updateHistoryById(history: ChatHistoryResponse, id: string, context: string) {
  const foundIndex = history.findIndex((item) => item.uuid === id);
  if (foundIndex !== -1) {
    history[foundIndex].context = context;
  }
  return history;
}

const chatReducer = (state = initialState, action: ActionType): typeof initialState => {
  switch (action.type) {
    // get all
    case chatActonType.GET_ALL_HISTORY:
      return {
        ...state,
      };
    case chatActonType.CLEAR_ALL_HISTORY:
      return {
        ...state,
        chatContexts: [],
      };

    case chatActonType.DEL_HISTORY:
      return {
        ...state,
        chatContexts: state.chatContexts.filter((item) => item.chatid !== action.payload),
      };
    case chatActonType.ADD_DETAIL:
      return {
        ...state,
        chatContexts: updateChatById(state.chatContexts, action.payload),
      };
    case chatActonType.ADD_HISTORY:
      return {
        ...state,
        history: [...state.history, action.payload],
      };
    case chatActonType.UPDATE_HISTORY:
      return {
        ...state,
        history: updateHistoryById(state.history, action.payload.id, action.payload.input),
      };
    case chatActonType.UPDATE_CURRENTDIALOG:
      return {
        ...state,
        currentDialog: { ...state.currentDialog, uuid: action.payload.id, context: action.payload.input, role: 'ai' },
      };
    default:
      return state;
  }
};

export default chatReducer;
